package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.Objects;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        // 对密码进行md5算法加密后的密码匹配
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //密码比对
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     *
     * @param employeeDTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        Employee e = new Employee();
//        属性拷贝
        BeanUtils.copyProperties(employeeDTO, e);
        e.setStatus(StatusConstant.ENABLE);
        // 使用aop统一处理
        //e.setCreateTime(LocalDateTime.now());
        //e.setUpdateTime(LocalDateTime.now());
        e.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
//        当前创建人
        // 使用aop统一处理
        //e.setCreateUser(BaseContext.getCurrentId());
        //e.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.save(e);
    }

    /**
     * 分页查询
     * @param dto
     * @return
     */
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<Employee> p = employeeMapper.page(dto);
        return new PageResult(p.getTotal(), p.getResult());
    }

    /**
     *启用禁用员工
     * @param status
     * @param id
     */
    @Override
    public void startOrBin(Integer status, Long id) {
//        构建一个对象进行封装数据
        Employee e = Employee.builder()
                .id(id)
                .status(status)
                // 使用aop统一管理
                //.updateTime(LocalDateTime.now())
                //.updateUser(BaseContext.getCurrentId())
                .build();
        employeeMapper.startOrBin(e);

    }

    /**
     * 通过id查
     * @param id
     * @return
     */
    @Override
    public Employee selectById(Long id) {
        Employee e =employeeMapper.selectById(id);
        return e ;
    }

    /**
     * 编辑员工
     * @param edto
     */
    @Override
    public void edi(EmployeeDTO edto) {
//        转换数据为Employee
        Employee employee = new Employee();
        // 使用aop统一管理
        //employee.setUpdateUser(BaseContext.getCurrentId());
        //employee.setUpdateTime(LocalDateTime.now());
        BeanUtils.copyProperties(edto,employee);
        employeeMapper.startOrBin(employee);
    }

    /**
     * 修改员工密码
     * @param dto

     */
    public void editPassword(PasswordEditDTO dto) {
//        不知道为什么前端传过来的id为空，直接调用线程获取id
        Long empId = BaseContext.getCurrentId();
        String o = dto.getOldPassword();
//        对密码进行md5算法加密后的密码匹配
        String oldPassword = DigestUtils.md5DigestAsHex(o.getBytes());
        Employee employee = employeeMapper.selectById(empId);
//      旧密码相同
        if (oldPassword.equals(employee.getPassword())){
//            封装对象
            Employee e = new Employee();
            e.setId(empId);
            e.setPassword(DigestUtils.md5DigestAsHex(dto.getNewPassword().getBytes()));
            employeeMapper.startOrBin(e);
        }
        else {
            throw  new PasswordErrorException(MessageConstant.PASSWORD_EDIT_FAILED);
        }
    }
}
